import axios from "axios";
import { message, Modal } from "antd";
import NProgress from "nprogress";
import { clear, get } from "./storage";
import { BASE_URL, TIMEOUT} from './config';

// const service = axios.create({
//     baseURL: process.env.PEACT_APP_BASE_API,
//     timeout: 5000
// })

const service = axios.create({
    baseURL:BASE_URL,
    timeout:TIMEOUT
})

service.interceptors.request.use(
    config => {
        NProgress.start();
        config.headers['Authorization'] = get('token')
        return config;
    },
    err => {
        console.log("请求超时");
        NProgress.done();
        return Promise.reject(err);
    }
)


// Add a response interceptor
service.interceptors.response.use(
    response => {
        NProgress.done();

        if (response.status === 200) {
            const { code } = response.data
            if (code === 4003) {
                message.warning('您的登陆状态已经丢失，请退出后重新登陆！')
                return Promise.reject('请登录')
            } else if (code === 4000) {
                clear()
                return Promise.reject('认证失败')
            }
            return response;
        } else {
            Modal.error({
                title: '网络请求错误'
            })
            return Promise.reject('网络请求错误！')
        }
    },
    error => {
        Modal.error({
            title: '网络请求错误'
        })
        NProgress.done();
        return Promise.reject(error);
    }
);

export default service
